package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void saveOrUpdate(Employee entity) {
        if (entity.getId() != null) {
            //更新操作
            employeeMapper.updateByPrimaryKey(entity);
            //维护与角色之间的关系
            employeeMapper.deleteRoleRelation(entity.getId());

        }else {
           Employee user = employeeMapper.selectByUsername(entity.getUsername());
            if (user != null) {
                throw new RuntimeException("用户名已存在");
            }
            employeeMapper.insert(entity);
        }
        //更新与新增都需要插入新的关系
        if (entity.getRoles() != null) {

        for (Role role : entity.getRoles()) {
        employeeMapper.insertRoleRelation(entity.getId(),role.getId());
        }
        }
    }

    @Override
    public void changeState(Long id) {
        employeeMapper.changeState(id);
    }

    @Override
    public Employee get(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> selectAll() {
        List<Employee> list = employeeMapper.selectAll();
        return list;
    }

   //检查用用户名
    public void checkUsername(String username) {
        Employee user = employeeMapper.selectByUsername(username);
        if (user != null) {
            throw new RuntimeException("用户名已存在");
        }
    }

    @Override
    public Long[] selectRoleById(Long id) {
        return employeeMapper.selectRoleById(id);
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = employeeMapper.rows(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result = new PageResult(rows, employeeMapper.queryForList(qo));
        return result;
    }
}
